<!DOCTYPE html>
<html>
<head>
    <%include("/back/_include/meta.html",{"title":""}){}%>
    <%include("/back/_include/style.html"){}%>
    <link href="/assets/back/plugin/zTree/css/zTreeStyle/zTreeStyle.css" rel="stylesheet" type="text/css">

</head>
<body class="gray-bg">
<div class="wrapper wrapper-content">
    <div class="row">
        <div class="col-sm-12">
            <div class="panel panel-default bk-bg-white">
                <div class="panel-heading bk-bg-white">
                    <a class="btn btn-xs btn-info" id="expandAllBtn">全部展开</a>
                    <a class="btn btn-xs btn-warning" id="resetBtn">全部收缩</a>
                </div>
                <div class="panel-body">
                    <ul id="zTreeMenuContent" class="ztree"></ul>
                </div>
            </div>
        </div>
    </div>
</div>
<button data-toggle="modal" class="hide" id="operator_modal_btn" href="#operator_modal"></button>
<div id="operator_modal" class="modal fade" aria-hidden="true" style="z-index: 2051!important;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body">
            </div>
        </div>
    </div>
</div>
<%include("/back/_include/script.html"){}%>
<script type="text/javascript" src="/assets/back/plugin/zTree/js/jquery.ztree.all-3.5.js"></script>
<script type="text/javascript">
    var setting = {
        async: {
            enable: true,
            url: "/b/menu/treeData",
            otherParam: {"systemId": '${systemId!}'},
            autoParam: ["id=id"],//, "name=n", "level=lv"
            dataFilter: filter,
            type: "post"
        },
        view: {
            fontCss: getFont,
            expandSpeed: "",
            addHoverDom: addHoverDom,
            removeHoverDom: removeHoverDom,
            selectedMulti: false
        },
        edit: {
            enable: true,
            removeTitle: "删除菜单",
            renameTitle: "编辑菜单名称"
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            beforeRemove: beforeRemove,	//节点被删除之前的事件,并且根据返回值确定是否允许删除操作
            beforeRename: beforeRename,	//用于捕获节点编辑名称结束

            beforeAsync: beforeAsync,	//用于捕获异步加载之前的事件回调函数,zTree 根据返回值确定是否允许进行异步加载
            onAsyncSuccess: onAsyncSuccess,	//用于捕获异步加载出现异常错误的事件回调函数
            onAsyncError: onAsyncError,	//用于捕获异步加载正常结束的事件回调函数

            beforeDrag: beforeDrag,	//用于捕获节点被拖拽之前的事件回调函数，并且根据返回值确定是否允许开启拖拽操作
            beforeDrop: beforeDrop,	//用于捕获节点拖拽操作结束之前的事件回调函数，并且根据返回值确定是否允许此拖拽操作
            beforeDragOpen: beforeDragOpen,	//用于捕获拖拽节点移动到折叠状态的父节点后，即将自动展开该父节点之前的事件回调函数，并且根据返回值确定是否允许自动展开操作
            onDrag: onDrag,	//用于捕获节点被拖拽的事件回调函数
            onDrop: onDrop,	//用于捕获节点拖拽操作结束的事件回调函数
            onExpand: onExpand	//用于捕获节点被展开的事件回调函数
        }
    };

    //节点数据过滤
    function filter(treeId, parentNode, childNodes) {
        if (!childNodes) {
            return null;
        }
        for (var i = 0, l = childNodes.length; i < l; i++) {
            childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
        }
        return childNodes;
    }

    //字体设置
    function getFont(treeId, node) {
        return node.font ? node.font : {};
    }

    ////////////////////下面是处理增删改节点//////////////////

    //节点被删除之前的事件,并且根据返回值确定是否允许删除操作
    function beforeRemove(treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("zTreeMenuContent");
        zTree.selectNode(treeNode);
        var result = false;
        if(confirm("确认删除<" + treeNode.name + ">菜单吗？")){
            var load = loading();
            postSync("/b/menu/delete",{"id": treeNode.id},function (res) {
                closeLoad(load)
                if(!res.success){
                    error(res.msg)
                    return;
                }
                msg("删除成功")
                result = true;
            },function () {
                closeLoad(load)
                systemErr();
            })
        }
        return result;
    }

    //用于捕获节点编辑名称
    function beforeRename(treeId, treeNode, newName, isCancel) {
        if (treeNode.name == newName) {
            return true;
        } else if (newName.length == 0) {
            error("菜单名称不能为空！");
            return false;
        }
        post("/b/menu/rename",{"id": treeNode.id, "name": newName},function (res) {
            if(!res.success){
                error(res.msg)
                return false;
            }
            msg("修改成功")
            return true;
        },function () {
            systemErr();
        })
    }

    //添加菜单
    var newCount = 1;

    function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) {
            return;
        }
        //1.处理添加按钮
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='添加菜单' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        var btn = $("#addBtn_" + treeNode.tId);
        if (btn) btn.bind("click", function () {
            var addName = "新增菜单" + (newCount++);//菜单初始化名称
            var orderId = (treeNode.children == undefined ? 1 : (treeNode.children.length + 1));
            post("/b/menu/save",{"pId": treeNode.id, "name": addName, "orderId": orderId},function (res) {
                if(!res.success){
                    error(res.msg)
                    return;
                }
                var zTree = $.fn.zTree.getZTreeObj("zTreeMenuContent");
                zTree.addNodes(treeNode, {id: res.data, pId: treeNode.id, name: addName});
                msg("新增菜单成功")
            },function () {
                systemErr();
            })
        });
        //3.菜单功能设置
        var operatorControlStr = "<span class='button operator' id='operatorControlBtn_" + treeNode.tId + "' title='菜单功能设置' onfocus='this.blur();'></span>";
        sObj.after(operatorControlStr);
        var operatorBtn = $("#operatorControlBtn_" + treeNode.tId);
        if (operatorBtn) operatorBtn.bind("click", function () {
            var id = treeNode.id;
//            layer.open({
//                type: 2,
//                title: '设置功能',
//                shadeClose: true,
//                shade: 0.2,
//                area: ['780px', '90%'],
//                content: "/b/menu/operatorTree?id="+id
//            });
            ajaxHtml("/b/menu/operatorTree?id="+id,function(res){
                if(res.success===false){
                    error("加载功能列表失败")
                    return;
                }
                configModal("#operator_modal", "功能列表", res);
                $('#operator_modal_btn').trigger("click");
            });
        });
    };

    function removeHoverDom(treeId, treeNode) {
        //1.处理添加按钮
        $("#addBtn_" + treeNode.tId).unbind().remove();

        //2.菜单参数设置
// 		$("#paramControlBtn_"+treeNode.tId).unbind().remove();

        //3.菜单功能设置
        $("#operatorControlBtn_" + treeNode.tId).unbind().remove();

        //4.菜单国际化名称设置
        $("#nameControlBtn_" + treeNode.tId).unbind().remove();
    };

    ////////////////////下面是处理展开//////////////////

    //用于捕获异步加载之前的事件回调函数,zTree 根据返回值确定是否允许进行异步加载
    function beforeAsync() {
        curAsyncCount++;
    }

    //用于捕获异步加载出现异常错误的事件回调函数
    function onAsyncSuccess(event, treeId, treeNode, msg) {
        curAsyncCount--;
        if (curStatus == "expand") {
            expandNodes(treeNode.children);
        } else if (curStatus == "async") {
            asyncNodes(treeNode.children);
        }

        if (curAsyncCount <= 0) {
            if (curStatus != "init" && curStatus != "") {
                //$("#demoMsg").text((curStatus == "expand") ? "全部展开完毕" : "后台异步加载完毕");
                asyncForAll = true;
            }
            curStatus = "";
        }
    }

    //用于捕获异步加载正常结束的事件回调函数
    function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
        curAsyncCount--;

        if (curAsyncCount <= 0) {
            curStatus = "";
            if (treeNode != null) asyncForAll = true;
        }
    }

    var curStatus = "init", curAsyncCount = 0, asyncForAll = false, goAsync = false;

    function expandAll() {
        if (!check()) {
            return;
        }
        var zTree = $.fn.zTree.getZTreeObj("zTreeMenuContent");
        if (asyncForAll) {
            //$("#demoMsg").text("已经异步加载完毕，使用 expandAll 方法");
            zTree.expandAll(true);
        } else {
            expandNodes(zTree.getNodes());
            if (!goAsync) {
                //$("#demoMsg").text("已经异步加载完毕，使用 expandAll 方法");
                curStatus = "";
            }
        }
    }

    function expandNodes(nodes) {
        if (!nodes) {
            return;
        }
        curStatus = "expand";
        var zTree = $.fn.zTree.getZTreeObj("zTreeMenuContent");
        for (var i = 0, l = nodes.length; i < l; i++) {
            zTree.expandNode(nodes[i], true, false, false);
            if (nodes[i].isParent && nodes[i].zAsync) {
                expandNodes(nodes[i].children);
            } else {
                goAsync = true;
            }
        }
    }

    function asyncAll() {
        if (!check()) {
            return;
        }
        var zTree = $.fn.zTree.getZTreeObj("zTreeMenuContent");
        if (asyncForAll) {
            //$("#demoMsg").text("已经异步加载完毕，不再重新加载");
        } else {
            asyncNodes(zTree.getNodes());
            if (!goAsync) {
                //$("#demoMsg").text("已经异步加载完毕，不再重新加载");
                curStatus = "";
            }
        }
    }

    function asyncNodes(nodes) {
        if (!nodes) {
            return;
        }
        curStatus = "async";
        var zTree = $.fn.zTree.getZTreeObj("zTreeMenuContent");
        for (var i = 0, l = nodes.length; i < l; i++) {
            if (nodes[i].isParent && nodes[i].zAsync) {
                asyncNodes(nodes[i].children);
            } else {
                goAsync = true;
                zTree.reAsyncChildNodes(nodes[i], "refresh", true);
            }
        }
    }

    function reset() {
        if (!check()) {
            return;
        }
        asyncForAll = false;
        goAsync = false;
        //$("#demoMsg").text("");
        $.fn.zTree.init($("#zTreeMenuContent"), setting);
    }

    function check() {
        if (curAsyncCount > 0) {
            //$("#demoMsg").text("正在进行异步加载，请等一会儿再点击...");
            return false;
        }
        return true;
    }

    ////////////////////下面是处理拖拽///////////////////

    function dropPrev(treeId, nodes, targetNode) {
        var pNode = targetNode.getParentNode();
        if (pNode && pNode.dropInner === false) {
            return false;
        } else {
            for (var i = 0, l = curDragNodes.length; i < l; i++) {
                var curPNode = curDragNodes[i].getParentNode();
                if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
                    return false;
                }
            }
        }
        return true;
    }

    function dropInner(treeId, nodes, targetNode) {
        if (targetNode && targetNode.dropInner === false) {
            return false;
        } else {
            for (var i = 0, l = curDragNodes.length; i < l; i++) {
                if (!targetNode && curDragNodes[i].dropRoot === false) {
                    return false;
                } else if (curDragNodes[i].parentTId && curDragNodes[i].getParentNode() !== targetNode && curDragNodes[i].getParentNode().childOuter === false) {
                    return false;
                }
            }
        }
        return true;
    }

    function dropNext(treeId, nodes, targetNode) {
        var pNode = targetNode.getParentNode();
        if (pNode && pNode.dropInner === false) {
            return false;
        } else {
            for (var i = 0, l = curDragNodes.length; i < l; i++) {
                var curPNode = curDragNodes[i].getParentNode();
                if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
                    return false;
                }
            }
        }
        return true;
    }

    //用于捕获节点被拖拽之前的事件回调函数，并且根据返回值确定是否允许开启拖拽操作
    var log, className = "dark", curDragNodes, autoExpandNode;

    function beforeDrag(treeId, treeNodes) {
        className = (className === "dark" ? "" : "dark");
        for (var i = 0, l = treeNodes.length; i < l; i++) {
            if (treeNodes[i].drag === false) {
                curDragNodes = null;
                return false;
            } else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
                curDragNodes = null;
                return false;
            }
        }
        curDragNodes = treeNodes;
        return true;
    }

    //用于捕获拖拽节点移动到折叠状态的父节点后，即将自动展开该父节点之前的事件回调函数，并且根据返回值确定是否允许自动展开操作
    function beforeDragOpen(treeId, treeNode) {
        autoExpandNode = treeNode;
        return true;
    }

    //用于捕获节点拖拽操作结束之前的事件回调函数，并且根据返回值确定是否允许此拖拽操作
    function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
        className = (className === "dark" ? "" : "dark");
        return true;
    }

    //用于捕获节点被拖拽的事件回调函数
    function onDrag(event, treeId, treeNodes) {
        className = (className === "dark" ? "" : "dark");
    }

    //用于捕获节点拖拽操作结束的事件回调函数
    function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
        className = (className === "dark" ? "" : "dark");
        //alert(treeNodes.length + ":"+treeNodes[0].id + ", " + (targetNode ? (targetNode.id + ", " + targetNode.name) : "isRoot" ));
        if (treeNodes.length > 0 && targetNode) {
            var dragId = treeNodes[0].id;//被拖拽菜单
            var targetId = targetNode.id;//拖拽到的目标菜单
            post("/b/menu/update", {"id": dragId, "pId": targetId}, function (res) {
                if (!res.success) {
                    msg("操作失败")
                    return
                }
                msg("编辑成功")
            }, function () {
                systemErr();
            })
        }
    }

    //用于捕获节点被展开的事件回调函数
    function onExpand(event, treeId, treeNode) {
        if (treeNode === autoExpandNode) {
            className = (className === "dark" ? "" : "dark");
        }
    }

    function setTrigger() {
        var zTree = $.fn.zTree.getZTreeObj("zTreeMenuContent");
        zTree.setting.edit.drag.autoExpandTrigger = $("#callbackTrigger").attr("checked");
    }

    //////////////////初始化////////////////////

    $(document).ready(function () {
        $.fn.zTree.init($("#zTreeMenuContent"), setting);
        $("#callbackTrigger").bind("change", {}, setTrigger);	//拖拽节点时自动展开父节点是否触发

        $("#expandAllBtn").bind("click", expandAll);	//全部展开
        //$("#asyncAllBtn").bind("click", asyncAll);	//背后展开
        $("#resetBtn").bind("click", reset);	//重置
    });

    //	setTimeout(function(){
    //		expandAll();
    //	}, 500);
</script>
</body>
</html>